package com.canbot.u05.activity.presidemode;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.R;
import com.canbot.u05.bean.guide.MapVoiceAndEyes;
import com.canbot.u05.bean.preside.PresideModule;
import com.canbot.u05.bean.preside.PresideTask;
import com.canbot.u05.bean.preside.PresideTaskNode;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.socket.MsgSendUtils;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.socket.StringMsgBean;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.StatusBarUtil;
import com.canbot.u05.utils.ToastTools;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author zmp
 * 主持任务添加节点界面
 */
public class AddTaskMainActivity extends BaseCompereActivity {

        private static final String TAG = "AddTaskMainActivity";

        @BindView(R.id.preside_cancel_iv)
        ImageView presideCancelIv;

        @BindView(R.id.preside_save_iv)
        ImageView presideSaveIv;

        @BindView(R.id.preside_lv)
        ListView presideLv;

        @BindView(R.id.preside_rcv)
        RecyclerView presideRcv;

        @BindView(R.id.preside_del)
        ImageView presideDel;

        @BindView(R.id.preside_task_name)
        TextView presideTaskName;

        private ToastTools toastTools;

        List<PresideTaskNode> taskNodeList;

        private RecyclerAdapter recyclerAdapter;

        private ItemTouchHelper itemTouchHelper;


        private PresideTaskNode currentTaskNode;

        private int currentPosition;

        private PresideTask presideTask;

        private View ivOk;

        private View ivPb;

        private TextView tvLoad;

        private int position;

        private PresideTaskNode currentPlayNode;

        private Dialog hintDialog;

        private boolean isSaveDialog;

        private LinearLayout renameLL;

        private boolean isFirstSetAction;

        private boolean isFirstLanguageVoice;

        private boolean isFirstDanceVoice;

        private boolean isFirstSetMove;

        private boolean isFirstSetMoveVoice;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main_add_task);
                ButterKnife.bind(this);
                EventBus.getDefault().register(this);
                isFirstSetAction = true;
                isFirstLanguageVoice = true;
                isFirstSetMove = true;
                isFirstSetMoveVoice = true;
                isFirstDanceVoice = true;
                PresideMoveSetting.isFirstMove = true;
                PresideMoveSetting.isFirstTurn = true;
                toastTools = ToastTools.newInstance(this);
                MapVoiceAndEyes.playMapVoiceAndEyes(MapVoiceAndEyes.voiceEyesList.get(19));
                initView();
        }

        private void initView() {
                presideLv.setAdapter(lvAdapter);
                presideLv.setOnItemClickListener(onItemClickListener);
                String taskInfo = getIntent().getStringExtra("taskInfo");
                position = getIntent().getIntExtra("position", -1);
                presideTask = JSON.parseObject(taskInfo, PresideTask.class);
                if (presideTask == null) {
                        taskNodeList = new ArrayList<>();
                        presideTask = new PresideTask();
                        presideTask.setTaskNodes(taskNodeList);
                }
                else {
                        taskNodeList = presideTask.getTaskNodes();
                        presideTaskName.setText(presideTask.getTaskName());
                }
                presideRcv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
                recyclerAdapter = new RecyclerAdapter(this, taskNodeList);
                itemTouchHelper = new ItemTouchHelper(new MyCallBack(recyclerAdapter));
                itemTouchHelper.attachToRecyclerView(presideRcv);
                presideRcv.setAdapter(recyclerAdapter);
        }

        class RecyclerAdapter extends RecyclerView.Adapter<MyHolder> {

                private final LayoutInflater layoutInflater;


                public List<PresideTaskNode> getList() {
                        return list;
                }

                private final List<PresideTaskNode> list;

                public RecyclerAdapter(Context context, List<PresideTaskNode> list) {
                        this.layoutInflater = LayoutInflater.from(context);
                        this.list = Collections.synchronizedList(list);
                }

                @Override
                public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                        View inflate = null;
                        switch (viewType) {
                                case PresideModule.DANCE_TYPE:
                                        inflate = layoutInflater.inflate(R.layout.preside_rv_item1, parent, false);
                                        break;
                                case PresideModule.LANGUAGE_TYPE:
                                        inflate = layoutInflater.inflate(R.layout.preside_rv_item2, parent, false);
                                        break;
                                case PresideModule.MOVE_TYPE:
                                        inflate = layoutInflater.inflate(R.layout.preside_rv_item3, parent, false);
                                        break;
                        }

                        return new MyHolder(inflate, viewType);
                }

                @Override
                public void onBindViewHolder(MyHolder holder, int position) {
                        PresideTaskNode presideTaskNode = list.get(position);
                        holder.position = position;
                        holder.updateView(presideTaskNode, getItemViewType(position));
                }

                @Override
                public int getItemCount() {
                        return list.size();
                }

                @Override
                public int getItemViewType(int position) {
                        return list.get(position).getType();
                }
        }

        class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener {


                public int position;

                private PresideTaskNode presideTaskNode;

                private TextView danceTv;

                private TextView languageTv;

                private TextView languageActionTv;

                private TextView moveLanguageTv;

                private TextView moveTv;

                private ImageView playIv;

                private TextView indexTv;

                public MyHolder(View itemView, int viewType) {
                        super(itemView);
                        playIv = (ImageView) itemView.findViewById(R.id.preside_play_iv);
                        indexTv = (TextView) itemView.findViewById(R.id.preside_index_tv);
                        switch (viewType) {
                                case PresideModule.DANCE_TYPE:
                                        danceTv = (TextView) itemView.findViewById(R.id.preside_dance_tv);
                                        danceTv.setOnClickListener(this);
                                        playIv.setOnClickListener(this);
                                        break;
                                case PresideModule.LANGUAGE_TYPE:
                                        languageTv = (TextView) itemView.findViewById(R.id.preside_language_content);
                                        languageTv.setOnClickListener(this);

                                        languageActionTv = (TextView) itemView.findViewById(R.id.preside_language_action);
                                        languageActionTv.setOnClickListener(this);
                                        playIv.setOnClickListener(this);
                                        break;
                                case PresideModule.MOVE_TYPE:
                                        moveTv = (TextView) itemView.findViewById(R.id.preside_move_content);
                                        moveTv.setOnClickListener(this);
                                        moveLanguageTv = (TextView) itemView.findViewById(R.id.preside_move_language);
                                        moveLanguageTv.setOnClickListener(this);
                                        playIv.setOnClickListener(this);
                                        break;
                        }

                        itemView.setOnTouchListener(new View.OnTouchListener() {
                                @Override
                                public boolean onTouch(View v, MotionEvent event) {
                                        if (event.getAction() == MotionEvent.ACTION_DOWN) {
                                                itemTouchHelper.startDrag(MyHolder.this);
                                        }
                                        return false;
                                }
                        });
                }

                @Override
                public void onClick(View v) {
                        currentTaskNode = presideTaskNode;
                        currentPosition = position;
                        switch (v.getId()) {
                                case R.id.preside_dance_tv:
                                        Intent intent = new Intent(AddTaskMainActivity.this, PresideDanceActivity.class);
                                        intent.putExtra("content", presideTaskNode.getDanceBean().content);
                                        if (isFirstDanceVoice) {
                                                isFirstDanceVoice = false;
                                                MapVoiceAndEyes.playMapVoiceAndEyes(MapVoiceAndEyes.voiceEyesList.get(20));
                                        }
                                        startActivityForResult(intent, REQ_ADD_DANCE);
                                        break;
                                case R.id.preside_play_iv:
                                        playTaskOrStop(!v.isSelected(), presideTaskNode);
                                        break;
                                case R.id.preside_language_content:
                                        intent = new Intent(AddTaskMainActivity.this, HostModeCustomModuleActivity.class);
                                        PresideTaskNode.LanguageBean languageBean = presideTaskNode.getLanguageBean();
                                        intent.putExtra("path", languageBean.voiceBean.path);
                                        intent.putExtra("content", languageBean.voiceBean.name);
                                        intent.putExtra("type", languageBean.voiceBean.languageType);
                                        intent.putExtra("isEnableNull", true);
                                        if (isFirstLanguageVoice) {
                                                isFirstLanguageVoice = false;
                                                MapVoiceAndEyes.playMapVoiceAndEyes(MapVoiceAndEyes.voiceEyesList.get(21));
                                        }
                                        startActivityForResult(intent, REQ_ADD_VOICE);
                                        break;
                                case R.id.preside_language_action:
                                        intent = new Intent(AddTaskMainActivity.this, PresideChooseAction.class);
                                        PresideTaskNode.LanguageBean languageBean1 = presideTaskNode.getLanguageBean();
                                        intent.putExtra("actionID", languageBean1.actionBean.actionId);
                                        intent.putExtra("actionName", languageBean1.actionBean.actionName);
                                        if (isFirstSetAction) {
                                                isFirstSetAction = false;
                                                MapVoiceAndEyes.playMapVoiceAndEyes(MapVoiceAndEyes.voiceEyesList.get(22));
                                        }
                                        startActivityForResult(intent, REQ_ADD_ACTION);
                                        break;
                                case R.id.preside_move_content:
                                        intent = new Intent(AddTaskMainActivity.this, PresideMoveActivity.class);
                                        intent.putExtra("direct", presideTaskNode.getMoveBean().orientation);
                                        intent.putExtra("num", presideTaskNode.getMoveBean().distance);
                                        intent.putExtra("speed", presideTaskNode.getMoveBean().speed);
                                        if (isFirstSetMove) {
                                                isFirstSetMove = false;
                                                MapVoiceAndEyes.playMapVoiceAndEyes(MapVoiceAndEyes.voiceEyesList.get(23));
                                        }
                                        startActivityForResult(intent, REQ_MOVE_ACTION);
                                        break;
                                case R.id.preside_move_language:
                                        intent = new Intent(AddTaskMainActivity.this, HostModeCustomModuleActivity.class);
                                        PresideTaskNode.MoveBean moveBean = presideTaskNode.getMoveBean();
                                        intent.putExtra("isEnableNull", true);
                                        intent.putExtra("path", moveBean.voiceBean.path);
                                        intent.putExtra("content", moveBean.voiceBean.name);
                                        intent.putExtra("type", moveBean.voiceBean.languageType);
                                        if (isFirstSetMoveVoice) {
                                                isFirstSetMoveVoice = false;
                                                MapVoiceAndEyes.playMapVoiceAndEyes(MapVoiceAndEyes.voiceEyesList.get(26));
                                        }
                                        startActivityForResult(intent, REQ_ADD_VOICE);
                                        break;
                        }
                }

                public void updateView(PresideTaskNode presideTaskNode, int itemViewType) {
                        this.presideTaskNode = presideTaskNode;
                        playIv.setSelected(presideTaskNode.isSelected());
                        indexTv.setText(String.valueOf(position + 1));
                        switch (itemViewType) {
                                case PresideModule.DANCE_TYPE:
                                        danceTv.setText(presideTaskNode.getDanceBean().content);
                                        break;
                                case PresideModule.LANGUAGE_TYPE:
                                        languageTv.setText(presideTaskNode.getLanguageBean().voiceBean.name);
                                        languageActionTv.setText(presideTaskNode.getLanguageBean().actionBean.actionName);
                                        break;
                                case PresideModule.MOVE_TYPE:
                                        moveTv.setText(presideTaskNode.getMoveBean().hasMoveContent());
                                        moveLanguageTv.setText(presideTaskNode.getMoveBean().voiceBean.name);
                                        break;
                        }
                }


        }

        private void playTaskOrStop(boolean isPlay, final PresideTaskNode presideTaskNode) {
                if (isPlay && checkEmptyData(presideTaskNode)) {
                        toastTools.showText("请先给模块添加内容!");
                        return;
                }
                showLoadDialog();
                HashMap<String, Object> hasMap = new HashMap<>();
                hasMap.put("type", isPlay ? HostModeListViewActivity.PRESIDE_SERVLET_TYPE_NODE_START : HostModeListViewActivity.PRESIDE_SERVLET_TYPE_NODE_STOP);
                hasMap.put("data", isPlay ? JSON.toJSONString(presideTaskNode) : "stop");
                OkHttpUtils.upLoadFile("http://" + IpMsgConst.SOCKET_HOST2 + ":7755/" + "presenterMsg", hasMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {
                                Logger.e(TAG, "onSuccess:" + result);
                                toastTools.showText("Success");
                                loadDialog.dismiss();
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                if (currentPlayNode != null && currentPlayNode != presideTaskNode && currentPlayNode.isSelected()) {
                                                        currentPlayNode.setSelected(false);
                                                }
                                                presideTaskNode.setSelected(!presideTaskNode.isSelected());
                                                currentPlayNode = presideTaskNode;
                                                recyclerAdapter.notifyDataSetChanged();
                                        }
                                });
                        }

                        @Override
                        public void onFailure() {
                                Logger.e(TAG, "onFailure");
                                toastTools.showText("服务器异常,请重试!");
                                loadDialog.dismiss();
                        }
                });
        }

        /**
         * 删除空模块!
         */
        private void deleteEmptyModule() {
                Iterator<PresideTaskNode> iterator = taskNodeList.iterator();
                while (iterator.hasNext()) {
                        PresideTaskNode next = iterator.next();
                        if (checkEmptyData(next)) {
                                iterator.remove();
                        }
                }
                recyclerAdapter.notifyDataSetChanged();
        }


        private boolean checkEmptyData(PresideTaskNode taskNodeBean) {
                int type = taskNodeBean.getType();
                switch (type) {
                        case PresideModule.DANCE_TYPE:
                                PresideTaskNode.DanceBean dance = taskNodeBean.getDanceBean();
                                if (TextUtils.isEmpty(dance.danceID)) {
                                        return true;
                                }
                                break;
                        case PresideModule.MOVE_TYPE:
                                PresideTaskNode.VoiceBean voiceBean = taskNodeBean.getMoveBean().voiceBean;
                                PresideTaskNode.MoveBean moveBean = taskNodeBean.getMoveBean();
                                boolean b = handlerMoveEvent(moveBean);
                                if (TextUtils.isEmpty(voiceBean.name)) {
                                        if (!b) {
                                                return true;
                                        }
                                }
                                break;
                        case PresideModule.LANGUAGE_TYPE:
                                PresideTaskNode.ActionBean actionBean = taskNodeBean.getLanguageBean().actionBean;
                                voiceBean = taskNodeBean.getLanguageBean().voiceBean;
                                boolean isRandom = false;
                                if (TextUtils.isEmpty(actionBean.actionId) || "-1".equals(actionBean.actionId)) {
                                        isRandom = true;
                                }
                                if (TextUtils.isEmpty(voiceBean.name) && isRandom) {
                                        return true;
                                }
                                break;
                }
                return false;
        }

        private boolean handlerMoveEvent(PresideTaskNode.MoveBean moveBean) {
                if (TextUtils.isEmpty(moveBean.speed)) {
                        return false;
                }
                float aFloat = Float.valueOf(moveBean.distance);
                if (aFloat <= 0) {
                        return false;
                }
                return true;
        }


        /**
         * 消息发布者位置
         * ReceiveData
         * mHandler
         * case MsgType.MOBILE_PAD_MAP_TASK:
         *
         * @param bean
         */
        @Subscribe(threadMode = ThreadMode.MAIN)
        public void onMapEvent(StringMsgBean bean) {
                switch (bean.getMsgType()) {
                        case MsgType.COMPERE_RAN_TASK_END:
                                toastTools.showText("任务结束!");
                                if (currentPlayNode != null && currentPlayNode.isSelected()) {
                                        currentPlayNode.setSelected(false);
                                        recyclerAdapter.notifyDataSetChanged();
                                }
                                break;
                }
        }

        @Override
        protected void onResume() {
                super.onResume();
                recyclerAdapter.notifyItemChanged(currentPosition);
        }

        public static final int REQ_ADD_DANCE = 1000;

        public static final int REQ_ADD_VOICE = 1001;

        public static final int REQ_ADD_ACTION = 1002;

        public static final int REQ_MOVE_ACTION = 1003;

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                if (resultCode == RESULT_OK) {
                        switch (requestCode) {
                                case REQ_ADD_DANCE:
                                        int type = data.getIntExtra("type", -1);
                                        String audioPath = data.getStringExtra("path");
                                        String content = data.getStringExtra("content");
                                        String actionID = data.getStringExtra("actionID");
                                        onDanceResult(type, audioPath, content, actionID);
                                        break;
                                case REQ_ADD_VOICE:
                                        type = data.getIntExtra("type", -1);
                                        audioPath = data.getStringExtra("path");
                                        content = data.getStringExtra("content");
                                        onAudioResult(type, audioPath, content);
                                        break;
                                case REQ_ADD_ACTION:
                                        actionID = data.getStringExtra("actionID");
                                        String actionName = data.getStringExtra("actionName");
                                        onActionResult(actionID, actionName);
                                        break;
                                case REQ_MOVE_ACTION:
                                        String direct = data.getStringExtra("direct");
                                        String num = data.getStringExtra("num");
                                        String speed = data.getStringExtra("speed");
                                        onMoveResult(direct, num, speed);
                                        break;
                        }
                }
        }


        private void onDanceResult(int type, String audioPath, String content, String actionID) {
                if (currentTaskNode.getType() == PresideModule.DANCE_TYPE) {
                        PresideTaskNode.DanceBean danceBean = currentTaskNode.getDanceBean();
                        danceBean.danceID = audioPath;
                        danceBean.content = content;
                        danceBean.actionID = actionID;
                }
        }

        private void onAudioResult(int type, String audioPath, String content) {
                switch (currentTaskNode.getType()) {
                        case PresideModule.LANGUAGE_TYPE:
                                PresideTaskNode.LanguageBean languageBean = currentTaskNode.getLanguageBean();
                                languageBean.voiceBean.languageType = type;
                                languageBean.voiceBean.path = audioPath;
                                languageBean.voiceBean.name = content;

                                break;
                        case PresideModule.MOVE_TYPE:
                                currentTaskNode.getMoveBean().voiceBean.path = audioPath;
                                currentTaskNode.getMoveBean().voiceBean.languageType = type;
                                currentTaskNode.getMoveBean().voiceBean.name = content;
                                break;
                }
        }

        private void onActionResult(String actionID, String actionName) {
                if (currentTaskNode.getType() == PresideModule.LANGUAGE_TYPE) {
                        PresideTaskNode.LanguageBean languageBean = currentTaskNode.getLanguageBean();
                        languageBean.actionBean.actionId = actionID;
                        languageBean.actionBean.actionName = actionName;
                }
        }

        private void onMoveResult(String direct, String num, String speed) {
                if (currentTaskNode.getType() == PresideModule.MOVE_TYPE) {
                        PresideTaskNode.MoveBean moveBean = currentTaskNode.getMoveBean();
                        moveBean.speed = speed;
                        moveBean.distance = num;
                        moveBean.orientation = direct;
                }
        }

        class MyCallBack extends ItemTouchHelper.Callback {

                private boolean isDelete;

                private RecyclerAdapter adapter;

                private MyHolder itemViewHolder;

                public MyCallBack(RecyclerAdapter adapter) {
                        this.adapter = adapter;
                }

                @Override
                public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                        int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                        int swipeFlags = 0;
                        return makeMovementFlags(dragFlags, swipeFlags);
                }

                @Override
                public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                        int adapterPosition = viewHolder.getAdapterPosition();
                        Log.e("Test", "adapterPosition:" + adapterPosition);
                        PresideTaskNode taskNode = taskNodeList.remove(adapterPosition);
                        taskNodeList.add(target.getAdapterPosition(), taskNode);
                        adapter.notifyItemMoved(adapterPosition, target.getAdapterPosition());
                        return true;
                }

                /**
                 * 滑动删除
                 *
                 * @param viewHolder
                 * @param direction
                 */
                @Override
                public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                }

                /**
                 * 长按拖长按拖拽删除 true  自己处理 false 调用 itemTouchHelper.startDrag(holder);
                 */
                @Override
                public boolean isLongPressDragEnabled() {
                        return false;
                }

                /**
                 * 滑动删除
                 *
                 * @return
                 */
                @Override
                public boolean isItemViewSwipeEnabled() {
                        return false;
                }


                /**
                 * 当拖拽开始的时候调用
                 *
                 * @param viewHolder
                 * @param actionState
                 */
                @Override
                public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
                        //拖拽的时候
                        if (actionState == ItemTouchHelper.ACTION_STATE_IDLE) {
                                isDelete = true;
                                int width = presideDel.getWidth();
                                int height = presideDel.getHeight();
                                int[] ints = new int[2];
                                int[] ints2 = new int[2];
                                presideDel.getLocationOnScreen(ints);
                                int w = itemViewHolder.itemView.getWidth();
                                int h = itemViewHolder.itemView.getHeight();
                                itemViewHolder.itemView.getLocationOnScreen(ints2);
                                Rect rect = new Rect(ints2[0], ints2[1], ints2[0] + w, ints2[1] + h);
                                Log.e("onItemClear", "rect:" + rect);
                                boolean contains = rect.contains(ints[0] + width / 2, ints[1] + height / 2);
                                Log.e("onItemClear", "contains:" + contains);
                                if (contains) {
                                        int adapterPosition = itemViewHolder.getAdapterPosition();
                                        Log.e("onItemClear", "contains:" + adapterPosition);
                                        taskNodeList.remove(adapterPosition);
                                        itemTouchHelper.onChildViewDetachedFromWindow(itemViewHolder.itemView);
                                        adapter.notifyItemRemoved(adapterPosition);
                                }
                                else {
                                        isDelete = false;
                                }
                        }
                        if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
                                isDelete = false;
                                if (viewHolder instanceof MyHolder) {
                                        //让ViewHolder知道Item开始选中
                                        itemViewHolder = (MyHolder) viewHolder;
                                }
                        }
                        super.onSelectedChanged(viewHolder, actionState);
                }

                @Override
                public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState,
                                        boolean isCurrentlyActive) {
                        if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
                                if (isDelete) {
                                        return;
                                }
                                int width = presideDel.getWidth();
                                int height = presideDel.getHeight();
                                int[] ints = new int[2];
                                int[] ints2 = new int[2];
                                presideDel.getLocationOnScreen(ints);
                                int w = viewHolder.itemView.getWidth();
                                int h = viewHolder.itemView.getHeight();
                                viewHolder.itemView.getLocationOnScreen(ints2);
                                Rect rect = new Rect(ints2[0], ints2[1], ints2[0] + w, ints2[1] + h);
                                Log.e("onItemClear", "rect:" + rect);
                                boolean contains = rect.contains(ints[0] + width / 2, ints[1] + height / 2);
                                Log.e("onItemClear", "contains:" + contains);
                                presideDel.setSelected(contains);
                        }
                        super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
                }

                @Override
                public void onChildDrawOver(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState,
                                            boolean isCurrentlyActive) {

                        if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
                                if (isDelete) {
                                        return;
                                }
                                int width = presideDel.getWidth();
                                int height = presideDel.getHeight();
                                int[] ints = new int[2];
                                int[] ints2 = new int[2];
                                presideDel.getLocationOnScreen(ints);
                                int w = viewHolder.itemView.getWidth();
                                int h = viewHolder.itemView.getHeight();
                                viewHolder.itemView.getLocationOnScreen(ints2);
                                Rect rect = new Rect(ints2[0], ints2[1], ints2[0] + w, ints2[1] + h);
                                Log.e("onItemClear", "rect:" + rect);
                                boolean contains = rect.contains(ints[0] + width / 2, ints[1] + height / 2);
                                Log.e("onItemClear", "contains:" + contains);
                                presideDel.setSelected(contains);
                        }
                        super.onChildDrawOver(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
                }

                /**
                 * 当拖拽结束的时候调用
                 *
                 * @param recyclerView
                 * @param viewHolder
                 */
                @Override
                public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                        super.clearView(recyclerView, viewHolder);
                        recyclerView.post(new Runnable() {
                                @Override
                                public void run() {
                                        presideDel.setSelected(false);
                                        adapter.notifyDataSetChanged();
                                }
                        });
                }
        }

        @Override
        protected void onDestroy() {
                super.onDestroy();
                EventBus.getDefault().unregister(this);
        }

        @Override
        protected void onPause() {
                super.onPause();
                if (currentPlayNode != null && currentPlayNode.isSelected()) {
                        currentPlayNode.setSelected(false);
                }
                MsgSendUtils.sendStringMsgToPad2(MsgType.COMPERE_RAN_TASK_END, "taskEnd");
        }

        @OnClick({R.id.preside_cancel_iv, R.id.preside_save_iv, R.id.preside_del})
        public void onViewClicked(View view) {
                switch (view.getId()) {
                        case R.id.preside_cancel_iv:
                                if (taskNodeList == null || taskNodeList.size() == 0) {
                                        finish();
                                }
                                else {
                                        showHintDialog(false);
                                }
                                break;
                        case R.id.preside_save_iv:
                                if (taskNodeList.size() == 0) {
                                        toastTools.showText("请先拖动添加任务模块!");
                                        return;
                                }
                                for (PresideTaskNode presideTaskNode : taskNodeList) {
                                        if (checkEmptyData(presideTaskNode)) {
                                                showHintDialog(true);
                                                return;
                                        }
                                }
                                showSaveTaskDialog(position == -1);
                                break;
                        case R.id.preside_del:
                                toastTools.showText("请将需要删除的任务内容拖至此处进行删除!");
                                break;
                }
        }

        private Dialog taskNameDialog;

        private EditText taskEditText;

        View.OnClickListener dialogClickListener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                        switch (v.getId()) {
                                case R.id.guide_dialog_rename_bt_sure:
                                        if (position == -1) {
                                                String name = taskEditText.getText().toString().trim();
                                                if (TextUtils.isEmpty(name)) {
                                                        toastTools.showText("任务名不能为空哦！");
                                                        return;
                                                }
                                                if (!name.matches("[\\u4E00-\\u9FA5A-Za-z0-9]+")) {
                                                        toastTools.showText("任务名含有非法字符哦！");
                                                        return;
                                                }


                                                for (PresideTask presenterTask : HostModeListViewActivity.mListData) {
                                                        if (name.equals(presenterTask.getTaskName())) {
                                                                toastTools.showText("任务名不能重复哦！");
                                                                return;
                                                        }
                                                }
                                                presideTask.setTaskName(name);
                                        }
                                        taskNameDialog.dismiss();
                                        addTask();
                                        break;
                                case R.id.guide_dialog_rename_bt_cancel:
                                        taskNameDialog.dismiss();
                                        break;
                                case R.id.guide_dialog_hint_sure:
                                        hintDialog.dismiss();
                                        if (isSaveDialog) {
                                                deleteEmptyModule();
                                                if (taskNodeList.size() == 0) {
                                                        toastTools.showText("请先拖动添加任务模块!");
                                                        return;
                                                }
                                                showSaveTaskDialog(position == -1);
                                        }
                                        else {
                                                finish();
                                        }
                                        break;
                                case R.id.guide_dialog_hint_move:
                                        hintDialog.dismiss();
                                        break;
                        }
                }
        };

        /**
         * 提示Dialog
         */
        private void showHintDialog(boolean isSave) {
                isSaveDialog = isSave;
                if (hintDialog == null) {
                        hintDialog = new Dialog(this, R.style.MyDialogStyle);
                        hintDialog.setContentView(R.layout.guide_dialog_hint);
                        Button sure = (Button) hintDialog
                                .findViewById(R.id.guide_dialog_hint_sure);
                        sure.setText(getString(R.string.sure));
                        sure.setOnClickListener(dialogClickListener);
                        Button move = ((Button) hintDialog
                                .findViewById(R.id.guide_dialog_hint_move));
                        move.setText(getString(R.string.cancel));
                        move.setOnClickListener(dialogClickListener);

                }
                String string;
                if (isSave) {
                        string = getString(R.string.task_save_hint);
                }
                else {
                        string = getString(R.string.task_exit_hint);
                }
                TextView textView = (TextView) hintDialog.findViewById(R.id.guide_dialog_tv);
                textView.setText(string);
                StatusBarUtil.hideVirtualKey(hintDialog);
                hintDialog.show();
        }


        private void addTask() {
                showLoadDialog();
                saveTaskData();
        }

        private void saveTaskData() {
                HashMap<String, Object> hasMap = new HashMap<>();
                hasMap.put("type", position == -1 ? HostModeListViewActivity.PRESIDE_SERVLET_TYPE_ADD : HostModeListViewActivity.PRESIDE_SERVLET_TYPE_UPDATE);
                hasMap.put("data", JSON.toJSONString(presideTask));
                OkHttpUtils.upLoadFile("http://" + IpMsgConst.SOCKET_HOST2 + ":7755/" + "presenterMsg", hasMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {
                                Logger.e(TAG, "onSuccess:" + result);
                                toastTools.showText("Success");
                                loadDialog.dismiss();
                                if (position == -1) {
                                        HostModeListViewActivity.mListData.add(presideTask);
                                }
                                else {
                                        HostModeListViewActivity.mListData.remove(position);
                                        HostModeListViewActivity.mListData.add(position, presideTask);
                                }
                                finish();

                        }

                        @Override
                        public void onFailure() {
                                Logger.e(TAG, "onFailure");
                                toastTools.showText("服务器异常,请重试!");
                                loadDialog.dismiss();
                        }
                });
        }


        private void showSaveTaskDialog(boolean isAdd) {
                if (taskNameDialog == null) {
                        taskNameDialog = new Dialog(this, R.style.MyDialogStyle);
                        taskNameDialog.setContentView(R.layout.guide_dialog_rename);
                        renameLL = (LinearLayout) taskNameDialog.findViewById(R.id.guide_dialog_ll);
                        taskEditText = (EditText) taskNameDialog.findViewById(R.id.guide_dialog_et);

                        taskNameDialog.findViewById(R.id.guide_dialog_rename_bt_sure).setOnClickListener(dialogClickListener);
                        taskNameDialog.findViewById(R.id.guide_dialog_rename_bt_cancel).setOnClickListener(dialogClickListener);
                }
                TextView textView = (TextView) taskNameDialog.findViewById(R.id.guide_dialog_title);
                TextView tv = (TextView) taskNameDialog.findViewById(R.id.guide_dialog_tv);
                if (isAdd) { //添加
                        textView.setText("任务命名");
                        tv.setVisibility(View.GONE);
                        renameLL.setVisibility(View.VISIBLE);
                        String taskName = presideTask.getTaskName();
                        if (TextUtils.isEmpty(taskName)) {
                                taskEditText.setText("");
                        }
                        else {
                                taskEditText.setText(taskName);
                        }
                }
                else { //修改
                        textView.setText("提示");
                        tv.setText("是否将更改保存到此任务中?");
                        tv.setVisibility(View.VISIBLE);
                        renameLL.setVisibility(View.GONE);
                }
                taskNameDialog.show();
        }


        List<PresideModule> lvList = new ArrayList<>();

        {
                lvList.add(new PresideModule(PresideModule.DANCE_TYPE, "舞蹈模块", R.drawable.preside_dance_selector));
                lvList.add(new PresideModule(PresideModule.LANGUAGE_TYPE, "语言模块", R.drawable.preside_language_selector));
                lvList.add(new PresideModule(PresideModule.MOVE_TYPE, "移动模块", R.drawable.preside_move_selector));
        }

        private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        if (taskNodeList.size() >= 99) {
                                toastTools.showText("已达到模块数上限!");
                                return;
                        }
                        PresideModule presideModule = lvList.get(position);
                        taskNodeList.add(taskNodeList.size(), new PresideTaskNode(presideModule.getType()));
                        recyclerAdapter.notifyItemInserted(taskNodeList.size());
                        presideRcv.scrollToPosition(taskNodeList.size() - 1);
                }
        };

        BaseAdapter lvAdapter = new BaseAdapter() {
                @Override
                public int getCount() {
                        return lvList == null ? 0 : lvList.size();
                }

                @Override
                public PresideModule getItem(int position) {
                        return lvList.get(position);
                }

                @Override
                public long getItemId(int position) {
                        return position;
                }

                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                        if (convertView == null) {
                                convertView = View.inflate(AddTaskMainActivity.this, R.layout.preside_lv_item, null);
                        }
                        TextView textView = (TextView) convertView.findViewById(R.id.preside_item_tv);
                        PresideModule item = getItem(position);
                        textView.setText(item.getContent());
                        textView.setBackgroundResource(item.getBg());
                        return convertView;
                }
        };

        private Dialog loadDialog;

        private void showLoadDialog() {
                if (loadDialog == null) {
                        loadDialog = new Dialog(this, R.style.MyDialogStyle);
                        loadDialog.setContentView(R.layout.guide_dialog_load);
                        ivOk = loadDialog.findViewById(R.id.guide_load_iv);
                        ivPb = loadDialog.findViewById(R.id.guide_load_pb);
                        tvLoad = (TextView) loadDialog.findViewById(R.id.guide_load_tv);
                }
                ivPb.setVisibility(View.VISIBLE);
                ivOk.setVisibility(View.INVISIBLE);
                tvLoad.setText("正在加载...");
                loadDialog.setCancelable(false);
                loadDialog.show();
        }
}
